package 网络编程;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class URL07 { //从指定地址下载文件
    public static void main(String[] args) {
        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            URL url = new URL("http://t7.baidu.com/it/u=3616242789,1098670747&fm=79&app=86&f=JPEG?w=900&h=1350");

            //获取链接
            urlConnection = (HttpURLConnection)url.openConnection();
            //连接
            urlConnection.connect();
            //获取流
            inputStream = urlConnection.getInputStream();

            outputStream = new BufferedOutputStream(new FileOutputStream(new File("E:\\FileTest\\temp.jpg")));
            byte[] array = new byte[1024];
            int len;
            while ((len = inputStream.read(array)) != -1){
                outputStream.write(array,0,len);
            }

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            //断开连接
            if(urlConnection != null){
                urlConnection.disconnect();
            }
        }
    }
}
